<?php

namespace App\Listeners\Subscriber;

use App\Events\Auth\Login;
use App\Events\Auth\Logout;
use App\Events\Auth\Attempting;
use App\Events\Auth\AttemptFailed;
use App\Events\Queue\JobFailed;
use Illuminate\Auth\Events\Login as SystemLogin;
use Illuminate\Auth\Events\Logout as SystemLogout;
use Illuminate\Auth\Events\Attempting as SystemAttempting;
use Illuminate\Auth\Events\Failed as SystemFailed;
use Illuminate\Queue\Events\JobFailed as SystemJobFailed;
use Illuminate\Http\Request;


class SystemSubscriber extends AbstractSubscriber
{

    /**
     * 监听系统内部事件, 再触发到应用事件
     *
     * @var array
     */
    protected $listen = [
        SystemLogin::class => 'login',
        SystemLogout::class => 'logout',
        SystemAttempting::class => 'attempting',
        SystemFailed::class => 'failed',
        SystemJobFailed::class => 'jobFailed'
    ];

    /**
     * 请求实例
     *
     * @var Request
     */
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 登录成功事件
     *
     * @param SystemLogin $login
     */
    public function login(SystemLogin $login)
    {
        event(new Login($login->user, $this->request->ip(), $this->request->userAgent(), $login->remember));
    }

    /**
     * 退出登录事件
     *
     * @param SystemLogout $logout
     */
    public function logout(SystemLogout $logout)
    {
        event(new Logout($logout->user));
    }

    /**
     * 尝试凭证登录事件
     *
     * @param SystemAttempting $attempting
     */
    public function attempting(SystemAttempting $attempting)
    {
        event(new Attempting($attempting->credentials, $attempting->remember));
    }

    /**
     * 凭证登录失败事件
     *
     * @param SystemFailed $failed
     */
    public function failed(SystemFailed $failed)
    {
        event(new AttemptFailed($failed->user, $failed->credentials));
    }

    /**
     * 队列任务执行失败
     *
     * @param SystemJobFailed $failed
     */
    public function jobFailed(SystemJobFailed $failed)
    {
        event(new JobFailed($failed->connectionName, $failed->job, $failed->exception));
    }
}